package org.springblade.common.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springblade.core.tool.api.R;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理，优先级最高
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	/**
	 * 数据库异常处理
	 * @param e
	 * @return
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(Throwable.class)
	public Map<String, Object> handleSQLException(Throwable e){
		log.error("服务器异常", e);

		StackTraceElement[] elements = e.getStackTrace();
		boolean isSQLError = Arrays.stream(elements).anyMatch(ele -> {
			return ele.getClassName().contains("org.mybatis") || ele.getClassName().contains("org.apache.ibatis.")
				|| ele.getClassName().contains("java.sql");
		});
		//Arrays.stream(elements).forEach(ele -> ele.get);
		Map<String, Object> result = new HashMap<>();
		result.put("code", 400);
		result.put("success", Boolean.FALSE);
		result.put("data", null);
		if (isSQLError) {
			//throw new Throwable("数据库错误");
			//return new ResponseEntity("数据库错误", HttpStatus.INTERNAL_SERVER_ERROR);
			//return R.fail("数据库错误");
			result.put("msg", "数据库错误");
		}
		else {
			result.put("msg", e.getMessage());
		}
		//throw e;
		//return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		//return R.fail(e.getMessage());
		return result;
	}
}
